#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


//声明线程函数和互斥量
void* thread_func(void *msg);
pthread_mutex_t mutex;


#define MSG_SIZE 512


int main()
{
	int res = -1;
	pthread_t thread;
	void *thread_result = NULL;
	char msg[MSG_SIZE] = {'\0'};
	//初始化互斥量，使用默认的互斥量属性
	res = pthread_mutex_init(&mutex, NULL);
	if(res != 0)
	{
		perror("pthread_mutex_init failed\n");
		exit(EXIT_FAILURE);
	}
	//创建子线程，并把msg作为线程函数的参数传递给thread_func
	res = pthread_create(&thread, NULL, thread_func, msg);
	if(res != 0)
	{
		perror("pthread_create failed\n");
		exit(EXIT_FAILURE);
	}
	//输入字符串，以串‘end’结束
	printf("Input some test. Enter 'end' to finish\n");
	//把互斥量mutex加锁，以确保同一时间只有该线程可以访问msg中的数据
	pthread_mutex_lock(&mutex);
	while(strcmp("end\n", msg) != 0)
	{
		if(strncmp("TEST", msg, 4) == 0)
		{
			strcpy(msg, "copy_data\n");
		}
		else
		{
			fgets(msg, MSG_SIZE, stdin);
		}
		//把互斥量mutex解锁，让其他的线程可以访问msg中的数据
		pthread_mutex_unlock(&mutex);
		sleep(1);//休眠1秒再继续循环，让其他线程有执行的机会
		pthread_mutex_lock(&mutex);
	}
	pthread_mutex_unlock(&mutex);
	printf("\nWaiting for thread finish...\n");
	//等待子线程结束
	res = pthread_join(thread, &thread_result);
	if(res != 0)
	{
		perror("pthread_join failed\n");
		exit(EXIT_FAILURE);
	}
	printf("Thread joined\n");
	//清理互斥量
	pthread_mutex_destroy(&mutex);
	exit(EXIT_SUCCESS);
}
void* thread_func(void *msg)
{
	int i = 0;
	char *ptr = msg;
	sleep(1);
	//把互斥量mutex加锁，以确保同一时间只有该线程可以访问msg中的数据
	pthread_mutex_lock(&mutex);
	while(strcmp("end\n", msg) != 0)
	{
		//把小写字母变成大写
		for(i = 0; ptr[i] != '\0'; ++i)
		{
			if(ptr[i] >= 'a' && ptr[i] <='z')
			{
				ptr[i] -= 'a' - 'A';
			}
		}
		printf("You input %d characters\n", i-1);
		printf("To uppercase: %s\n", ptr);
		//把互斥量mutex解锁，让其他的线程可以访问msg中的数据
		pthread_mutex_unlock(&mutex);
		sleep(1);//休眠1秒再继续循环，让其他线程有执行的机会
		pthread_mutex_lock(&mutex);
	}
	pthread_mutex_unlock(&mutex);
	//退出线程
	pthread_exit(NULL);
}
